import { Location } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { STColumn } from '@delon/abc/st';
import { _HttpClient } from '@delon/theme';
import { NzFormatEmitEvent } from 'ng-zorro-antd/core/tree/public-api';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Api } from 'src/app/shared/api/api';
import { DELETED_STATUS_BADGE } from 'src/app/shared/constant/common-constant';
import { ResponseCode } from 'src/app/shared/response.code';

@Component({
  selector: 'app-system-role-menu',
  templateUrl: './role-menu.component.html'
})
export class RoleMenuComponent implements OnInit {
  role: any = {};

  currentMenu: any;
  currentMenuPermissions: any[] = [];

  permissionList: any[] = [];

  menuTree: any[] = [];

  permissionColmuns: STColumn[] = [
    { title: '序号', type: 'no', width: 60 },
    { title: '权限', index: 'permission' },
    { title: '备注', index: 'remark' },
    { title: '状态', index: 'deleted', type: 'badge', badge: DELETED_STATUS_BADGE, width: 100 },
    { title: '开启', render: 'operation', width: 100 }
  ];

  constructor(public msg: NzMessageService, private http: _HttpClient, private location: Location, private router: ActivatedRoute) {
    this.router.queryParams.subscribe((res: any) => {
      if (!res) {
        this.msg.error('参数有误');
        return;
      }
      this.role = res;
    });
  }

  ngOnInit(): void {
    this.queryMenuConfig();
  }

  backList() {
    this.location.back();
  }

  queryMenuConfig() {
    this.http.get(`${Api.BaseAntMenuApi}role/config/vo`, { roleId: this.role.id }).subscribe((res: any) => {
      if (res && res.code === ResponseCode.SUCCESS) {
        this.setMenuConfig(res.data);
      } else {
        this.setMenuConfig(null);
      }
    });
  }

  setMenuConfig(data: any): void {
    if (!data) {
      this.menuTree = [];
    } else {
      this.menuTree = data;
    }
  }

  menuClick(event: NzFormatEmitEvent): void {
    console.log(event);
    this.currentMenu = event.node?.origin['menu'];
    this.currentMenuPermissions = event.node?.origin['permissionList'] || [];
  }

  refreshPermission(index: number, event: any) {
    this.currentMenuPermissions[index].checked = event;
    this.currentMenuPermissions[index].selected = event;
  }

  save() {
    this.http.post(`${Api.BaseAntMenuApi}role/config/vo/${this.role.id}`, this.menuTree).subscribe((res: any) => {
      if (res && res.code === ResponseCode.SUCCESS) {
        this.queryMenuConfig();
        this.msg.success('保存成功!');
      } else {
        this.msg.error(res ? (res.message ? res.message : '保存失败，未知原因') : '保存失败，未知原因');
      }
    });
  }
}
